package profile

import (
	"context"
	"errors"
	"strconv"

	"usercenter/internal/biz"
	"usercenter/internal/middleware"
	"usercenter/internal/svc"
	"usercenter/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PostSuggestionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPostSuggestionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PostSuggestionLogic {
	return &PostSuggestionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PostSuggestionLogic) PostSuggestion(req *types.SuggestionRequest) (resp *types.SuggestionResponse, err error) {
    // 1. 安全检查：确保依赖服务已初始化
    // if l == nil || l.svcCtx == nil || l.email == nil {
    //     return nil, &biz.BizError{
    //         Code:    500,
    //         Message: "系统服务未正确初始化",
    //     }
    // }

    // 2. 参数校验
    if req.Email == "" {
        return nil, &biz.BizError{
            Code:    400,
            Message: "联系方式不能为空",
        }
    }
    if req.Suggestion == "" {
        return nil, &biz.BizError{
            Code:    400,
            Message: "反馈内容不能为空",
        }
    }

    // 3. 获取用户信息
    userId, ok := l.ctx.Value(middleware.UserIdKey).(int)
    if !ok || userId == 0 {
        return nil, &biz.BizError{
            Code:    401,
            Message: "未授权访问",
        }
    }

    user, err := l.svcCtx.UserModel.FindById(userId)
    if err != nil {
        l.Logger.Errorf("查询用户信息失败: %v", err)
        return nil, &biz.BizError{
            Code:    500,
            Message: "系统错误，请稍后再试",
        }
    }

    // 4. 调用邮件服务
    err = l.svcCtx.EmailServer.ForwardFeedbackToAdmin(
        strconv.Itoa(userId),
        user.Name,
        req.Email,
        req.Suggestion,
    )
    if err != nil {
        if errors.Is(err, context.DeadlineExceeded) {
            return nil, &biz.BizError{
                Code:    504,
                Message: "提交超时，请稍后再试",
            }
        }

        l.Logger.Errorf("提交反馈失败 - 用户ID: %d - 错误: %v", userId, err)
        return nil, &biz.BizError{
            Code:    500,
            Message: "反馈提交失败，请稍后再试",
        }
    }

    // 5. 记录日志（包含更多上下文信息）
    l.Logger.Infof("用户反馈已提交 - 用户ID: %d - 用户名: %s - 邮箱: %s", 
        userId, user.Name, req.Email)

	err = l.svcCtx.UserModel.AddCredits(userId, 1)
	l.Logger.Infof("反馈加积分 - 用户ID: %d - 错误: %v", userId, err)
	if err != nil {
		l.Logger.Errorf("反馈加积分错误 - 用户ID: %d - 错误: %v", userId, err)
	}
	// 可持久化到数据库

    // 6. 返回响应
    return &types.SuggestionResponse{
        Code:    200,
        Message: "反馈已提交，我们会尽快处理",
    }, nil
}